import { SpecimenEntity } from "@scmt/api-lis-specimen";
import { useData } from "./data";
type PrePrintCallback = (params: {
  specimens: SpecimenEntity[];
  mergeSpecimens: SpecimenEntity[][];
}) => void;

type EditObj = Record<string, SpecimenEntity[]>;

const _editingObj = ref<null | EditObj>(null);
const _printData = ref<SpecimenEntity[]>([]);
let _callback: PrePrintCallback = () => void 0;
export const usePrePrint = () => {
  const { groupedData, groupSpecimen } = useData();
  const printDataMerMap = computed(() => groupSpecimen(_printData.value));

  /**
   *
   * @param source
   * @param callback
   */
  const prePrint = (
    source: SpecimenEntity | SpecimenEntity[],
    callback: PrePrintCallback
  ) => {
    if (typeof callback !== "function") return;
    _printData.value = ([] as SpecimenEntity[]).concat(source);

    const couldMergeKey = Object.keys(printDataMerMap.value).filter(
      (key) => groupedData.value[key]?.length > 1
    );

    if (couldMergeKey.length > 0) {
      _callback = callback;
      _editingObj.value = couldMergeKey.reduce(
        (acc, cur) => ({ ...acc, [cur]: groupedData.value[cur] }),
        {} as EditObj
      );
    } else {
      callback({
        specimens: ([] as SpecimenEntity[]).concat(source),
        mergeSpecimens: [],
      });
    }
  };

  const onSaved = (model: EditObj) => {
    if (model) {
      const couldMergeKeys = Object.keys(model).filter((k) =>
        Boolean(model[k])
      );

      const normalSpecimens = _printData.value.filter(
        (item) => !couldMergeKeys.includes(item.checkId || "")
      );

      const mergeSpecimens = couldMergeKeys.reduce((acc, k) => {
        acc.push(groupedData.value[k] || []);

        return acc;
      }, [] as Array<SpecimenEntity[]>);

      if (typeof _callback === "function") {
        _callback({
          specimens: normalSpecimens,
          mergeSpecimens,
        });
      }
    }

    _editingObj.value = null;
    _callback = () => void 0;
  };

  return {
    prePrint,
    editingObj: _editingObj,
    onSaved,
  };
};
